package main

import (
	"crypto/md5"
	"encoding/json"
	"fmt"
	"io"
	"io/ioutil"
	"log"
	"regexp"
)

type KugouStruct struct {
	Status  int             `json:"status"`
	ErrCode int             `json:"err_code"`
	Data    KugouStructData `json:"data"`
}

type KugouStructAuthors struct {
	AuthorName string `json:"author_name"`
	Avatar     string `json:"avatar"`
}

type KugouStructData struct {
	Hash       string               `json:"hash"`
	AudioName  string               `json:"audio_name"`
	AlbumName  string               `json:"album_name"`
	Img        string               `json:"img"`
	AuthorName string               `json:"author_name"`
	PlayURL    string               `json:"play_url"`
	Authors    []KugouStructAuthors `json:"authors"`
}

// 酷狗歌曲地址

type KugouSong struct {
	TransParam KugouSongTransParam `json:"trans_param"`
	FileHead   int                 `json:"fileHead"`
	Q          int                 `json:"q"`
	FileSize   int                 `json:"fileSize"`
	FileName   string              `json:"fileName"`
	Status     int                 `json:"status"`
	URL        []string            `json:"url"`
	ExtName    string              `json:"extName"`
	BitRate    int                 `json:"bitRate"`
	TimeLength int                 `json:"timeLength"`
}

type KugouSongTransParam struct {
	Display     int `json:"display"`
	DisplayRate int `json:"display_rate"`
}

// 获取歌曲名字
func (kg *KugouStruct) getName() string {
	return kg.Data.AudioName
}

func (kg *KugouStruct) getAlbumName() string {
	return kg.Data.AlbumName
}
func (kg *KugouStruct) getPic() string {
	return kg.Data.Img
}
func (kg *KugouStruct) getDownloadURL() string {
	// 歌曲key加密计算 hash + kgcloudv2 + appid + mid + userid 115500
	// http://trackercdn.kugou.com/i/v2/?cmd=26&key=33264683f470d56521775db4aef78bcf&hash=0DB27531BB7B32F8928CC92F3DDDE6F9&behavior=play&mid=0&appid=1155&userid=0&version=0&vipType=0&token=0&pid=4
	w := md5.New()
	io.WriteString(w, kg.Data.Hash+"kgcloudv2"+"1155"+"0"+"0")
	key := fmt.Sprintf("%x", w.Sum(nil))

	songURL := fmt.Sprintf(
		"http://trackercdn.kugou.com/i/v2/?cmd=26&key=%s&hash=%s&behavior=play&mid=0&appid=%s&userid=0&version=0&vipType=0&token=0&pid=4",
		key, kg.Data.Hash, "1155")
	response := Get(songURL)
	defer response.Body.Close()
	songData, err := ioutil.ReadAll(response.Body)

	var song KugouSong

	err = json.Unmarshal(songData, &song)

	if err != nil {
		fmt.Println("解析JSON失败", err)
	}

	if len(song.URL) == 0 {
		log.Fatal("获取歌曲下载地址失败")
	}

	return song.URL[0]
}
func (kg *KugouStruct) getSinger() string {
	return kg.Data.AuthorName
}

func parseByKg(musicURL string) (music *Music) {
	response := Get(musicURL)
	defer response.Body.Close()
	body, _ := ioutil.ReadAll(response.Body)
	// 需要个hash 来获取歌曲信息
	regx := regexp.MustCompile(`"hash":"(\w+)"`)

	songId := regx.FindStringSubmatch(string(body))
	kugouInfo := genKuGouModel(songId[1])

	return &Music{
		Name:     kugouInfo.getName(),
		URL:      kugouInfo.getDownloadURL(),
		AlbumPic: kugouInfo.getPic(),
		Album:    kugouInfo.getAlbumName(),
		Singer:   kugouInfo.getSinger(),
	}
}

// 获取酷狗歌曲信息
func genKuGouModel(songId string) (kugou *KugouStruct) {
	detailURL := fmt.Sprintf(
		"http://www.kugou.com/yy/index.php?r=play/getdata&hash=%s&mid=cb9402e79b3c2b7d4fc13cbc85423190",
		songId)
	response := Get(detailURL)
	defer response.Body.Close()
	body, err := ioutil.ReadAll(response.Body)

	if err != nil {
		fmt.Println(err)
		return
	}
	err = json.Unmarshal(body, &kugou)

	if err != nil {
		fmt.Println(err)
		return
	}
	return kugou

}
